<template>
  <div v-if="visible" class="modal-overlay">
    <div class="modal-card">
      <button class="close-btn" @click="emitClose">×</button>
      <h2 class="title">确认支付</h2>
      <div class="content">
        <p><strong>用户名：</strong>{{ userName }}</p>
        <p>
          <strong>订单金额：</strong><span class="price">￥{{ totalPrice }}</span>
        </p>
        <p v-if="balance !== null"><strong>当前余额：</strong>￥{{ balance }}</p>
        <p v-else class="loading-text">正在加载余额...</p>
        <div class="order-details">
          <h3>订单详情</h3>
          <div v-for="(item, index) in orderItems" :key="index" class="order-item">
            <p>
              <strong>{{ item.name }}</strong> x {{ item.quantity }}
            </p>
            <p class="item-price">￥{{ item.price * item.quantity }}</p>
          </div>
        </div>
      </div>
      <div class="actions">
        <button class="btn pay-btn" :disabled="isPaying || balance === null" @click="handlePay">
          {{ isPaying ? '支付中...' : '立即支付' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

interface OrderItem {
  name: string
  price: number
  quantity: number
  mealId?: number
  mealType?: string
}

const props = defineProps<{
  visible: boolean
  userName: string
  orderItems: OrderItem[]
  totalPrice: number
  trainTicketOrderId?: number
}>()

const emits = defineEmits(['close', 'success', 'fail'])
const balance = ref<number | null>(null)
const isPaying = ref(false)

watch(
  () => props.visible,
  (val) => {
    if (val) fetchBalance()
  },
)

async function fetchBalance() {
  try {
    const res = await fetch(
      `http://localhost:9000/api/users?username=${encodeURIComponent(props.userName)}`,
    )
    if (!res.ok) throw new Error('获取失败')
    const data = await res.json()
    // 从用户对象中提取余额字段
    balance.value = data.balance || 0
  } catch (e) {
    console.error('余额获取失败', e)
    balance.value = 0
  }
}

function emitClose() {
  emits('close')
}

async function handlePay() {
  if (balance.value === null) return
  if (balance.value < props.totalPrice) {
    emits('fail', { status: 'insufficient_balance' })
    emitClose()
    return
  }

  isPaying.value = true
  try {
    // 使用统一订单服务创建火车餐订单
    const payRes = await fetch('http://localhost:9000/api/orders/train-meal', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        username: props.userName,
        trainTicketOrderId: props.trainTicketOrderId,
        totalPrice: props.totalPrice,
        items: props.orderItems.map((item) => ({
          mealId: item.mealId || 1, // 需要从orderItems中获取mealId
          mealName: item.name,
          mealType: item.mealType || '主食', // 需要从orderItems中获取mealType
          price: item.price,
          quantity: item.quantity,
          subtotal: item.price * item.quantity,
        })),
      }),
    })
    if (!payRes.ok) {
      const errorData = await payRes.json()
      throw new Error(errorData.message || '订单创建失败')
    }
    const result = await payRes.json()
    if (result.success) {
      emits('success', {
        status: 'ok',
        orderId: result.orderId,
        orderNumber: result.orderNumber,
        paymentStatus: result.paymentStatus,
        inventoryStatus: result.inventoryStatus,
        messageStatus: result.messageStatus,
      })
    } else {
      throw new Error(result.message || '订单创建失败')
    }
  } catch (e: unknown) {
    console.error('支付或订单创建失败', e)
    const errorMessage = e instanceof Error ? e.message : '未知错误'
    emits('fail', { status: 'network_error', message: errorMessage })
  } finally {
    isPaying.value = false
    emitClose()
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.modal-card {
  background-color: #fff;
  border-radius: 16px;
  padding: 24px;
  width: 400px;
  position: relative;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
  text-align: center;
  animation: fadeIn 0.3s ease;
}

.close-btn {
  position: absolute;
  top: 12px;
  right: 16px;
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
}

.title {
  margin-bottom: 16px;
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.content p {
  margin: 10px 0;
  font-size: 16px;
  color: #555;
}

.price {
  color: #e53935;
  font-weight: bold;
  font-size: 18px;
}

.loading-text {
  font-size: 14px;
  color: #999;
}

.order-details {
  margin-top: 20px;
  text-align: left;
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.order-details h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 10px;
}

.order-item {
  display: flex;
  justify-content: space-between;
  margin: 8px 0;
  font-size: 14px;
}

.item-price {
  color: #e53935;
}

.actions {
  margin-top: 20px;
}

.btn {
  width: 100%;
  padding: 12px;
  border: none;
  border-radius: 8px;
  color: white;
  font-size: 15px;
  cursor: pointer;
}

.pay-btn {
  background-color: #2196f3;
}

.btn:disabled {
  background-color: #aaa;
  cursor: not-allowed;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}
</style>
